<template>
  <el-dialog v-model="dialogVisible" title="上传你心爱的照片吧" width="50%" draggable :close-on-click-modal="false">
    <el-form ref="ruleFormRef" label-width="120px" class="demo-ruleForm"
             :model="ruleForm" :rules="rules" size="default" status-icon>
      <el-form-item label="标签类型：" prop="tag">
        <el-select-v2 style="width: 100%"
                      placeholder="请输入标签类型" v-model="ruleForm.tag" :options="tagOptions" clearable
                      filterable multiple collapse-tags collapse-tags-tooltip :max-collapse-tags="3"/>
      </el-form-item>
      <el-form-item>
        <el-upload class="upload-container" drag multiple ref="uploadRef"
                   :action="actionUrl" :auto-upload="false"
                   :show-file-list="true"
                   :on-change="handleAvatarChange"
                   :before-upload="beforeAvatarUpload">
          <el-icon class="el-icon--upload">
            <upload-filled/>
          </el-icon>
          <div class="el-upload__text">
            拖拽文件或 <em>点击上传</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              请上传大小不超过2MB的jpeg、jpg、png格式的图片！
            </div>
          </template>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancelDialog">取消</el-button>
        <el-button type="primary" @click="confirmDialog(ruleFormRef)">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts">
import {defineComponent, getCurrentInstance, reactive, ref} from 'vue'
import type {FormInstance, FormRules, UploadProps, UploadInstance, UploadFile, UploadFiles} from 'element-plus'
import {UploadFilled} from '@element-plus/icons-vue'
import {useCategoryStore} from "@/stores/category";
import {ipcApiRoute, httpPostForm} from '@/api/router'

type RuleForm = {
  tag: string[],
  imageUrls: UploadFile[]
}

export default defineComponent({
  components: {UploadFilled},
  setup(props, {emit, slots, attrs}) {

    const instance: any = getCurrentInstance()
    const {$ipc, $getHttpHost} = instance.appContext.config.globalProperties
    const {categoryList: tagOptions} = useCategoryStore()

    // 图片上传
    const actionUrl = ref('')
    /**
     * 获取图片上传地址
     */
    const getHost = () => {
      $getHttpHost().then((res: string) => {
        const uri = ipcApiRoute.uploadFile;
        actionUrl.value = res + '/' + uri.split('.').join('/');
      })
    }
    getHost()

    const uploadRef = ref<UploadInstance>()
    /**
     * 图片上传
     * @param uploadFile
     * @param uploadFiles
     */
    const handleAvatarChange: UploadProps['onChange'] = (uploadFile: UploadFile, uploadFiles: UploadFiles) => {
      ruleForm.imageUrls = uploadFiles
    }
    /**
     * 图片上传前
     * @param rawFile
     */
    const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
      if (!['image/jpeg', 'image/jpg', 'image/png'].includes(rawFile.type)) {
        ElMessage.error('请上传jpeg、jpg、png格式的图片！')
        return false
      } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('图片大小不能超过2MB！')
        return false
      }
      return true
    }

    // 表单相关
    const ruleFormRef = ref<FormInstance>()
    const ruleForm = reactive<RuleForm>({
      tag: [],
      imageUrls: []
    })
    const rules = reactive<FormRules>({
      tag: [
        {
          type: 'array',
          required: true,
          message: '请选择标签类型',
          trigger: 'blur',
        },
      ],
    })

    // 弹窗相关
    const dialogVisible = ref(false)
    /**
     * 打开弹窗
     */
    const openDialog = () => {
      dialogVisible.value = true
    }
    /**
     * 取消弹窗
     */
    const cancelDialog = () => {
      ruleForm.tag = []
      ruleForm.imageUrls = []
      dialogVisible.value = false
    }
    /**
     * 确认弹窗
     * @param formEl
     */
    const confirmDialog = async (formEl: FormInstance | undefined) => {
      if (!formEl) return
      await formEl.validate((valid, fields) => {
        if (valid) {
          if (!ruleForm.imageUrls.length) {
            ElMessage.error('请上传图片！')
            return
          }

          let formData = new FormData()
          ruleForm.imageUrls.forEach(img => {
            formData.append('file', img.raw)
          })
          // todo:v1.1 传递分类到后台，根据分类分目录存储
          httpPostForm(actionUrl.value, formData).then((res: any) => {
            ElMessage.success(res.message)
          }).finally(() => {
            cancelDialog()
          })
        }
      })
    }

    return {
      dialogVisible, openDialog, cancelDialog, confirmDialog,
      ruleFormRef, ruleForm, rules, tagOptions, uploadRef,
      actionUrl, handleAvatarChange, beforeAvatarUpload
    }
  }
})
</script>

<style scoped lang="less">
.upload-container {
  width: 100%;

  :deep(.el-upload-dragger) {
    background-color: #d9ecff;

    .el-icon--upload, .el-upload__text {
      color: #67c23a;
    }
  }

  :deep(.el-upload__tip) {
    color: #f56c6c;
  }
}
</style>
